package com.dashu.device.service;

import com.dashu.base.utils.CopyUtil;
import com.dashu.base.utils.VerificationUtil;
import com.dashu.device.dto.DeviceDTO;
import com.dashu.device.model.Device;
import com.dashu.device.model.QDevice;
import com.querydsl.core.BooleanBuilder;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.persistence.FlushModeType;
import javax.transaction.Transactional;

@Slf4j
@Service
public class DeviceService extends DataService {


    @Transactional
    public DeviceDTO updataByDeviceUUId(String uuid, String ip) {
        QDevice qDevice = QDevice.device;
        BooleanBuilder booleanBuilder = new BooleanBuilder();
        booleanBuilder.and(qDevice.uuid.eq(uuid));
        Device device =
                queryFactory
                        .select(qDevice)
                        .from(qDevice)
                        .where(booleanBuilder.getValue())
                        .fetchOne();
        if (device == null) return null;
        if (StringUtils.isEmpty(ip))
            ip = VerificationUtil.getRequestIp();
        device.setIp(ip);
        device.setBind(1);
        device = entityManager.merge(device);
//        entityManager.flush();
        entityManager.setFlushMode(FlushModeType.AUTO);
        DeviceDTO deviceDTO = CopyUtil.copyEnty(device, DeviceDTO.class);
        return deviceDTO;

    }

    public DeviceDTO findByDeviceUUId(String uuid) {
        QDevice qDevice = QDevice.device;
        BooleanBuilder booleanBuilder = new BooleanBuilder();
        booleanBuilder.and(qDevice.uuid.eq(uuid));
        Device device = queryFactory
                .select(qDevice)
                .from(qDevice)
                .where(booleanBuilder.getValue())
                .fetchOne();
        if (device == null)
            return null;
        DeviceDTO deviceDTO = CopyUtil.copyEnty(device, DeviceDTO.class);
        return deviceDTO;

    }

}
